var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");
layui.use(['tableEdit', 'table', 'form', 'laydate',"selectInput"], function () {
    let tableEdit = layui.tableEdit,
        layer = layui.layer,
        laydate = layui.laydate,
        selectInput = layui.selectInput;
    //客户信息
    let customerInfo = [];
    //币种
    let currencyInfo = [];
    //美元编码
    let usdCode = "";
    //美元
    let usdName = "";
    //美金汇率
    let usdRate = "";
    //美金对人名币汇率
    let rmbRate = "";
    //公司信息
    let companyInfo = [];
    //业务员
    let salesmanInfo = [];
    //附件
    let annexList = [];
    layer.ready(function () {
        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    companyInfo = data.data;
                    let initCode = "";
                    let initName = "";
                    for (let i in data.data) {
                        if (data.data[i].isProxy == 1) {
                            initCode = data.data[i].code;
                            initName = data.data[i].name;
                        }
                        //公司名称
                        $('#voucherCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if (initCode.length > 0) {
                        $('#voucherCompanyCode').val(initCode);
                        $('#voucherCompanyName').val(initName);
                    }
                    getBankAndDeptInfo(initCode);
                    form.render('select');
                }
            }
        });


        //获取当前登陆用户名称
        $("#founder").val(user.name);

        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            success: function (data) {
                if (data.status == 200) {
                    salesmanInfo = data.data;
                    for (let i in salesmanInfo) {
                        $("#salesmanCode").append(new Option(salesmanInfo[i].name, salesmanInfo[i].code));
                    }
                }
            }
        });

        //获取币种
        $.ajax({
            url: "receivePayment/getCurrencyInfo",
            success: function (data) {
                if (data.status == 200) {
                    currencyInfo = data.data;
                    for (let i in data.data) {
                        if (data.data[i].englishName == "USD") {
                            //美元编码
                            usdCode = data.data[i].code;
                            //美元名称
                            usdName = data.data[i].name;
                            //获取美金兑人名币汇率
                            rmbRate = data.data[i].exchangeRate;

                            $("#rmbRate").val(rmbRate);
                        } else if (data.data[i].englishName == "RMB") {
                            //人名币兑美元汇率
                            usdRate = data.data[i].exchangeRate;
                        }
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if (usdCode.length > 0) {
                        //默认USD选中
                        $('#currencyCode').val(usdCode);
                        $('#currency').val(usdName);
                        //美元汇率为1
                        $('#usdRate').val(1);
                    }
                    form.render('select');
                }
            }
        });

        //生成最新收款单号
        getNewBillNo();
    })
    form.render('select');

    //生成最新收款单号
    function getNewBillNo(){
        let flag = false;
        $.ajax({
            url:"receivePayment/getReceivePaymentBillNo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    //单号：RTCO+yyyyMMdd+3位有序数字
                    let billNo = data.data;
                    $("#billNo").val(billNo);
                    flag = true;
                }else {
                    layer.msg(data.msg, {icon: 5});
                }
            }
        });
        return flag;
    }

    //入账金额
    //收汇金额 = 入账金额 + 银行扣费(外)
    $("#entryAmount").blur(function(){
        //入账金额
        let entryAmount = $("#entryAmount").val();
        if (!isNumber(entryAmount)) {
            layer.msg('请输入数字');
            return;
        }
        entryAmount = new BigNumber(entryAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
        $("#entryAmount").val(entryAmount);
        //银行扣费(外)
        let bankDeductionExcept = $("#bankDeductionExcept").val();
        let collectionAmount = new BigNumber(entryAmount).plus(bankDeductionExcept).dp(2, BigNumber.ROUND_HALF_UP).toString();
        $("#collectionAmount").val(collectionAmount);
        //待认领金额 = 收汇金额-已认领金额
        $("#toBeClaimed").val(collectionAmount);

        form.render();
    })

    //银行扣费（外）
    //收汇金额 = 入账金额 + 银行扣费(外)
    $('#bankDeductionExcept').bind('input propertychange', function() {
        //入账金额
        let entryAmount = $("#entryAmount").val();
        if (!isNumber(entryAmount)) {
            layer.msg('请输入数字');
            return;
        }
        //银行扣费(外)
        let bankDeductionExcept = $("#bankDeductionExcept").val();
        if (!isNumber(bankDeductionExcept)) {
            layer.msg('请输入数字');
            return;
        }
        let collectionAmount = new BigNumber(entryAmount).plus(bankDeductionExcept).dp(2, BigNumber.ROUND_HALF_UP).toString();
        $("#collectionAmount").val(collectionAmount);
        //待认领金额 = 收汇金额-已认领金额
        $("#toBeClaimed").val(collectionAmount);

        form.render();
    });



    //监听币种下拉框
    form.on('select(currencyCode)', function (data) {
        if (data.value === "") {
            return;
        }
        let englishName = getCurrencyInfoByCode(data.value, 1);
        if (englishName == "RMB") {
            //如果选择rmb，则对应rmb汇率为1
            $("#rmbRate").val(1);
            $("#usdRate").val(usdRate);
        } else if (englishName == "USD") {
            //如果选择美元，则对应美金汇率为1
            $("#rmbRate").val(rmbRate);
            $("#usdRate").val(1);
        } else {
            //其它
            let exchangeRate = getCurrencyInfoByCode(data.value, 3);
            $("#usdRate").val(exchangeRate);
            $("#rmbRate").val(rmbRate);
        }
        let name = getCurrencyInfoByCode(data.value, 2);
        $("#currency").val(name);
    })

    //获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
    function getCurrencyInfoByCode(code, type) {
        for (let i in currencyInfo) {
            if (currencyInfo[i].code == code) {
                let res = "";
                switch (type) {
                    case 1:
                        res = currencyInfo[i].englishName;
                        break;
                    case 2:
                        res = currencyInfo[i].name;
                        break;
                    case 3:
                        res = currencyInfo[i].exchangeRate;
                        break;
                }
                return res;
            }
        }
        return "";
    }

    //客户名称
    let ins = selectInput.render({
        elem: '#customerSelect',
        name: 'customerSelect',
        hasSelectIcon: true,
        placeholder: '请输入名称',
        data: [],
    })
    //监听输入
    ins.on('itemInput(customerSelect)', function (obj) {
        let tempData = [];
        $.ajax({
            url: "basicInformation/getCustomerInfo?info=" + obj.value,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                    for (let i in customerInfo) {
                        customerInfo[i]["value"] = customerInfo[i].code;
                        tempData.push(customerInfo[i]);
                    }
                }
            }
        })
        ins.addSelect(tempData);
    })

    // 监听select 选择事件
    ins.on('itemSelect(customerSelect)', function (obj) {
        let code = obj.data;
        let name = obj.textContent;
        $("#customerCode").val(code);
        $("#customerName").val(name);
    });


    //监听业务员下拉框
    form.on("select(salesmanCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesman').val(salesmanInfo[i].name);
                break;
            }
        }
    });


    //监听制单公司下拉框
    form.on("select(voucherCompanyCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getCompanyInfoByCode(data.value);
        $("#voucherCompanyName").val(name);
        //重新查询银行信息和部门信息
        getBankAndDeptInfo(data.value);

    });

    function getBankAndDeptInfo(code) {
        //获取银行账号
        let defaultCode = "";
        $.ajax({
            url: "receivePayment/getBankAccountInfo?code=" + code,
            success: function (res) {
                if (res.status == 200) {
                    //银行信息
                    let bankAccountList = res.data.bankAccountList;
                    $('#accountNo').empty();
                    for (let i in bankAccountList) {
                        if (defaultCode.length == 0 && bankAccountList[i].defaultBusinessUse == 1) {
                            defaultCode = bankAccountList[i].code;
                        }
                        $('#accountNo').append(new Option(bankAccountList[i].name + "_" + bankAccountList[i].bankAccount, bankAccountList[i].code));
                    }
                    if (defaultCode.length > 0) {
                        $('#accountNo').val(defaultCode);
                    }

                    form.render('select');
                }
            }
        });
    }

    function getCompanyInfoByCode(code) {
        for (let i in companyInfo) {
            if (companyInfo[i].code == code) {
                return companyInfo[i].name;
            }
        }
        return "";
    }

    //监听提交
    form.on('submit(form-element)', function (data) {
        addData(data, 1);
    });
    form.on('submit(form-element2)', function (data) {
        addData(data, 2);
    });

    function addData(data, save) {
        //向后台组装数据
        let accId = $("[name='accountNo']").val()
        let accountName = $("[name='accountNo']").children("[value=" + accId + "]").text()
        //获取头部表单数据
        let req = data.field;
        let customerName = req.customerSelect;
        if(isEmpty(customerName)){
            layer.msg("客户名称不能为空！", {icon: 5});
            return false;
        }
        req["customerName"] = customerName;
        //银行名称
        req.accountName = accountName;
        //1:登记箱 2:招领箱
        req.save = save;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];

        req["annexList"] = annexReqs;
        let datas = JSON.stringify(req);
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            data: datas,
            url: "receivePayment/add",
            success: function (res) {
                if (res.status == 200) {
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/Money/collection.jsp");
                        parent.intab("views/jsp/Money/collection.jsp", "收款")
                        parent.detab("views/jsp/Money/tpl/newupcollection.jsp" + (id == '' ? '' : '?id=' + id));
                    },1000);
                    return false;
                } else {
                    if(res.status == 11005){
                        //单号已存在,需要生成新的单号
                        let flag = getNewBillNo();
                        if(flag){
                            layer.msg("单号已存在，已为您生成新的单号!", {icon: 6});
                        }else {
                            layer.msg("网络繁忙，请重新尝试！", {icon: 5});
                        }
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            }
        });
    }

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName',event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for (let i in data) {
                let flag = true;
                for (let j in annexList) {
                    if (data[i].id == annexList[j].id) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function (res) {
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for (var i in data) {
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data: annexList}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function () {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], {type: 'application/force-download'});

                //解决下载不存在文件的问题，根据blob大小判断
                if (blob.size == 0) {
                    layer.msg('服务器没找到此文件，请联系管理员!');
                } else {
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3, 5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data: annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName'){
            onLineFile(data.filePath);
        }
    });

//---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });


//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
    function getNowFormatDate(type) {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (1 == type) {
            let currentDate = year + separator + month + separator + strDate;
            return currentDate;
        } else if (2 == type) {
            let second = date.getMilliseconds().toString();
            if (second.length < 3) {
                if (second.length == 1) {
                    second = "0" + "0" + second;
                } else {
                    second = "0" + second;
                }
            }
            let currentDate = year.toString() + month.toString() + strDate.toString() + second;
            return currentDate;
        }

    }

    let currentDate = getNowFormatDate(1);
//收款时间
    laydate.render({
        elem: '#time',
        value: currentDate,
        isInitValue: true
    });


//提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    function isNumber(val) {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});